package com.midi.wholesale.ui;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JLabel;
import java.awt.Color;
import javax.swing.SwingConstants;
import java.awt.Component;
import javax.swing.JComboBox;
import java.awt.Dimension;
import javax.swing.JTextField;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.swing.JButton;
import javax.swing.ImageIcon;

import com.midi.wholesale.main.PasswordChecker;
import com.midi.wholesale.main.addElements;
import com.midi.wholesale.ui.DatePicker;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.midi.wholesale.main.*;
import com.midi.wholesale.models.Agent;
import com.midi.wholesale.models.Item;
import com.midi.wholesale.models.Lorry;
import com.midi.wholesale.models.Route;
import javax.swing.JList;

public class AddToLorry extends JFrame {

	private JPanel contentPane;
	
	public static final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
	private JTextField textDate;
	private JTable tableItems;
	private JTextField ci_agentName_textField;
	ListSelectionListener listSelectionListenerAgency;
	ListSelectionListener listSelectionListenerlorry;
	ListSelectionListener listSelectionListenerroute;
	ListSelectionListener listSelectionListeneritem;
	
	static String ValAgency;
	static String Vallorry;
	static String ValRoute;
	static String ValItem;
	
	private JComboBox ld_route_combo = new JComboBox();
	private JComboBox ld_agent_combo = new JComboBox();
	
	private ArrayList lorries;
	private ArrayList routes;
	private ArrayList agents;
	private ArrayList items = new ArrayList();
	
	
	private JList agents_list;
	private JList lorry_list;
	private JList route_list;
	private JList item_list;
	
	
	
	private JTextField de_date_text;
	private JTextField sd_amount_text;
	
	
	
	private int addElementTabClickCount;
	

	
	ListSelectionListener listSelectionListenerItem;
	

	DefaultListModel modelAgency = new DefaultListModel();
	DefaultListModel modelLorry = new DefaultListModel();
	DefaultListModel modelRoute = new DefaultListModel();
	DefaultListModel modelItem = new DefaultListModel();
	
	
	private JTextField ci_lorryName_textField;
	private JTextField ci_routeName_textField;
	private JTextField ci_itemName_textField;
	
	private static JTextField textFromDate;
	private static JTextField textToDate;
	
	Lorry selectedLorry;
	
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AddToLorry frame = new AddToLorry();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public AddToLorry() {
		
		setResizable(false);
		final JFrame home = this;
		setTitle("WholeSale v1.0 - Lathpandura Holdings");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 538, 694);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		//contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.setLayout(null);	
		
		tabbedPane.setBounds(10,10,500,634);
		contentPane.add(tabbedPane);
		
		JPanel loadLorryPanel = new JPanel();
		loadLorryPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
		tabbedPane.addTab("Delivery", null, loadLorryPanel, null);
		loadLorryPanel.setLayout(null);
		
		JLabel lblLorry = new JLabel("Lorry");
		lblLorry.setBounds(105, 24, 46, 18);
		loadLorryPanel.add(lblLorry);
		
		JLabel lblAgent = new JLabel("Sales Agent");		
		lblAgent.setBounds(86, 302, 77, 14);
		loadLorryPanel.add(lblAgent);			
		
		
		final JComboBox ld_lorry_combo = new JComboBox();
		ld_lorry_combo.setBounds(246, 24, 168, 20);
		loadLorryPanel.add(ld_lorry_combo);
		
				
		final JComboBox ld_agent_combo = new JComboBox();
		ld_agent_combo.setBounds(227, 300, 168, 20);
		loadLorryPanel.add(ld_agent_combo);
		
				
		JLabel lblRoute = new JLabel("Route");
		lblRoute.setBounds(86, 344, 46, 14);
		loadLorryPanel.add(lblRoute);
		
		final JComboBox ld_route_combo = new JComboBox();
		ld_route_combo.setBounds(227, 342, 168, 20);
		loadLorryPanel.add(ld_route_combo);
		
		ld_lorry_combo.removeAllItems();
		ld_lorry_combo.insertItemAt("Choose Lorry", 0);
		ld_lorry_combo.setSelectedIndex(0);
		
		ld_agent_combo.removeAllItems();
		ld_agent_combo.insertItemAt("Choose Agent",0);
		ld_agent_combo.setSelectedIndex(0);					
	
		ld_route_combo.removeAllItems();
		ld_route_combo.insertItemAt("Choose Route",0);
		ld_route_combo.setSelectedIndex(0);
		
		ArrayList<Agent> agentList = Common.loadagents();
		for (Agent agent : agentList) {
			ld_agent_combo.addItem(agent);
		}
		
				
		ArrayList<Lorry> lorryList = Common.loadlorries();
		for (Lorry lorry : lorryList) {
			ld_lorry_combo.addItem(lorry);
		}
		
		ArrayList<Route> routeList = Common.loadroutes();
		for (Route route : routeList) {
			ld_route_combo.addItem(route);
		}
		JLabel lblDate = new JLabel("Date");
		lblDate.setBounds(86, 395, 46, 14);
		loadLorryPanel.add(lblDate);
		
		textDate = new JTextField();
		textDate.setBounds(227, 392, 168, 20);
		loadLorryPanel.add(textDate);
		textDate.setColumns(10);
		
		JButton buttonCalendar = new JButton("");
		buttonCalendar.setIcon(new ImageIcon(AddToLorry.class.getResource("/com/midi/wholesale/resources/date.gif")));
		buttonCalendar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				textDate.setText(new DatePicker(home).setPickedDate());
			}
		});
		buttonCalendar.setBounds(405, 391, 21, 23);
		loadLorryPanel.add(buttonCalendar);
		
		JScrollPane lorry_table_scrollPane = new JScrollPane();
		lorry_table_scrollPane.setBounds(74, 67, 340, 131);
		loadLorryPanel.add(lorry_table_scrollPane);
		
		tableItems = new JTable(){  
			  public boolean isCellEditable(int row,int column){  
			    return column != 0;  
			  }  
			}; 
		lorry_table_scrollPane.setViewportView(tableItems);
		tableItems.setCellSelectionEnabled(true);		
		tableItems.setModel(new DefaultTableModel(
			new Object[][] {

			},
			new String[] {
				"Item Name", "Amount"
			}
		));
		
				
		JButton lbl_btnLoadExisting = new JButton("Load Existing");
		lbl_btnLoadExisting.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {
				if ( !ld_lorry_combo.getSelectedItem().toString().equals("Choose Lorry") /*&& 
						!ld_agent_combo.getSelectedItem().toString().equals("Choose Agent") &&
						!ld_route_combo.getSelectedItem().toString().equals("Choose Route")*/ ) {
					ArrayList<HashMap<String,String>> items = Common.loadDelivery((Lorry)ld_lorry_combo.getSelectedItem());
					selectedLorry = (Lorry)ld_lorry_combo.getSelectedItem();
					ArrayList<String> allItemlist = new ArrayList();
					ArrayList<Item> tempallItemlist = Common.loadItems();
					
					for (Item it : tempallItemlist) {
						allItemlist.add(it.toString());
					}
					
					int i;
					Object[][] modelArray =null;
					
					//if(tempallItemlist.size()<items.size()){
					//	modelArray = new Object[items.size()][2];
					//}
					modelArray = new Object[items.size()][2];
					for ( i = 0; i < items.size(); i++ ) {
						modelArray[i][0] = items.get(i).get("item_name");
						modelArray[i][1] = items.get(i).get("amount");
						allItemlist.remove(items.get(i).get("item_name"));
					}
					
					System.out.println(allItemlist);
					for (String it : allItemlist) {											
						//modelArray[i][0] = it;
						//modelArray[i][1] = null;
						i++;
					}
					
					tableItems.setModel(new DefaultTableModel(modelArray,
							new String[] {
								"Item Name", "Amount"
							}
						));
				}
			}
		});
		lbl_btnLoadExisting.setBounds(93, 226, 132, 23);
		loadLorryPanel.add(lbl_btnLoadExisting);
		
		JButton lbl_btnSubmitChanges = new JButton("Submit Changes");
		lbl_btnSubmitChanges.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String itemName = "",amount = "";
				for (int i = 0; i < tableItems.getRowCount(); i++) {  
					for (int j = 0; j < tableItems.getColumnCount(); j++) {
					   //rowData[i] = table.getValueAt(0, i); 
					//System.out.print(tableItems.getValueAt(i, j));
					if(j==0)
						itemName = tableItems.getValueAt(i, j).toString();
					if(j==1){
						if(tableItems.getValueAt(i, j)==null)
							continue;
						amount = tableItems.getValueAt(i, j).toString();
						System.out.println(itemName+amount);
						Common.editDelivery(selectedLorry.getName(), itemName, amount);
						
						}
					
					}					
				}
				
			}
		});
		lbl_btnSubmitChanges.setBounds(263, 226, 151, 23);
		loadLorryPanel.add(lbl_btnSubmitChanges);
		

		
		//////////////////////////////////////////////////////////////////////
		//create item panel
		JPanel addElementPanel = new JPanel();
		tabbedPane.addTab("Add Elements", null, addElementPanel, null);
		addElementPanel.setLayout(null);
		
		JPanel itemPanel = new JPanel();
		itemPanel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		itemPanel.setLayout(null);
		itemPanel.setBounds(8, 11, 483, 176);
		addElementPanel.add(itemPanel);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(235, 11, 238, 127);
		itemPanel.add(scrollPane);
		
		JLabel lblItemName = new JLabel("Name  :");
		lblItemName.setBounds(32, 64, 50, 14);
		itemPanel.add(lblItemName);
		
		ci_agentName_textField = new JTextField();
		ci_agentName_textField.setBounds(91, 64, 92, 14);
		itemPanel.add(ci_agentName_textField);
		ci_agentName_textField.setColumns(10);
		
		
		JButton ci_agentAdd_btn = new JButton("Add");
		ci_agentAdd_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< karama code
				// add new Agency to the System
				String newAgency = ci_agentName_textField.getText();

				
				boolean updateDB=true;
				Iterator itr = agents.iterator();
	
				//check for the duplicate values in the list
			
				if(!newAgency.trim().equals("")){
					while (itr.hasNext()) {
						String returnVal=itr.next().toString();
						if(newAgency.equalsIgnoreCase(returnVal)){
							updateDB=false;
							
						}

					}
					
					if(updateDB){
						
						DefaultListModel newAgencyModel = (DefaultListModel) agents_list.getModel();
						newAgencyModel.addElement(newAgency);
						agents_list.setModel(newAgencyModel);
						addElements.editAgency(newAgency, "add");
						clearFields(1);
						
						//update the agency arraylist after insertion of new element
						int sizeOfArray=newAgencyModel.getSize();
						//System.out.println(newAgencyModel.elementAt(0));
						agents.clear();
						//int j=1;
						for (int i = 0; i < sizeOfArray; i++) {
							System.out.println(newAgencyModel.elementAt(i));
							agents.add(newAgencyModel.elementAt(i));
						//j++;
						}
						
					}
				
					else{
					
						JOptionPane.showMessageDialog(null, "Duplicate value please Enter a different Name"); 
						ci_agentName_textField.setText("");	
					
			
					}
				}
				else{  
					JOptionPane.showMessageDialog(null, "Please Enter a value Before Add"); 
					ci_agentName_textField.setText("");	

				}
				
		
		  
			}
		});
		ci_agentAdd_btn.setBounds(91, 109, 82, 23);
		itemPanel.add(ci_agentAdd_btn);
		
		JLabel lblAddItem = new JLabel("Add Agent");
		lblAddItem.setFont(new Font("Tahoma", Font.BOLD, 16));
		lblAddItem.setBounds(22, 11, 95, 36);
		itemPanel.add(lblAddItem);
		
		listSelectionListenerAgency = new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent listSelectionEvent) {
				boolean adjust = listSelectionEvent.getValueIsAdjusting();
				// System.out.println(", Adjusting? " + adjust);
				if (!adjust) {
					JList list = (JList) listSelectionEvent.getSource();
					int selections[] = list.getSelectedIndices();
					Object selectionValues[] = list.getSelectedValues();
					for (int i = 0, n = selections.length; i < n; i++) {
						if (i == 0) {
						}
						ValAgency = (String) selectionValues[i];
						System.out.println(" Selections valAgency: "
								+ ValAgency);
					}
				}
			}
		};
		
		JButton ad_agentRemoveButton = new JButton("Remove");
		ad_agentRemoveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				// check if selection value from the list is not null
				if (ValAgency != null) {

					DefaultListModel newAgencyModel = (DefaultListModel) agents_list
							.getModel();
					
					//if(Common.updateTransactionsOnAgencyDelete(ValAgency)){
					
					newAgencyModel.removeElement(agents_list.getSelectedValue());
					agents_list.setModel(newAgencyModel);
					addElements.editAgency(ValAgency, "remove");
					
					//update the agency arraylist
					//set agency arraylist with the values in the list model
					
					
					int sizeOfArray=newAgencyModel.getSize();
					//System.out.println(newAgencyModel.elementAt(0));
					agents.clear();
					//int j=1;
					for (int i = 0; i < sizeOfArray; i++) {
						System.out.println(newAgencyModel.elementAt(i));
						agents.add(newAgencyModel.elementAt(i));
					//j++;
					}
					//String [] newAgencyArr =(String[]) newAgencyModel.toArray();
					//Collections.addAll(agency, newAgencyArr); 
					}
					
					if(ValAgency==null)
						JOptionPane.showMessageDialog(null, "Select an Agency first");
					else
						JOptionPane.showMessageDialog(null, "You deleted "+ ValAgency+" Agency"); 
						//ad_region_textField.setText("");	
					
						
					
					
				
			}
		});
		ad_agentRemoveButton.setBounds(384, 142, 89, 23);
		itemPanel.add(ad_agentRemoveButton);
		
		// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< karama code
		agents_list = new JList(modelAgency);
		scrollPane.setViewportView(agents_list);
		agents_list.setFont(new Font("Arial", Font.BOLD, 11));
		agents_list.setBorder(new TitledBorder(null, "Agent List", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		agents_list.setBackground(UIManager.getColor("Button.highlight"));
		
		JPanel panel = new JPanel();
		panel.setLayout(null);
		panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		panel.setBounds(8, 196, 483, 176);
		addElementPanel.add(panel);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(235, 11, 238, 127);
		panel.add(scrollPane_1);
		
		lorry_list = new JList(modelLorry);
		lorry_list.setFont(new Font("Arial", Font.BOLD, 11));
		lorry_list.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Lorry List", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		lorry_list.setBackground(Color.WHITE);
		scrollPane_1.setViewportView(lorry_list);
		
		JLabel label = new JLabel("Name  :");
		label.setBounds(32, 64, 50, 14);
		panel.add(label);
		
		ci_lorryName_textField = new JTextField();
		ci_lorryName_textField.setColumns(10);
		ci_lorryName_textField.setBounds(91, 64, 92, 14);
		panel.add(ci_lorryName_textField);
		
		JButton ci_lorryAdd_btn = new JButton("Add");
		ci_lorryAdd_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				String newlorry = ci_lorryName_textField.getText();

				
				boolean updateDB=true;
				Iterator itr = lorries.iterator();
	
				//check for the duplicate values in the list
			
				if(!newlorry.trim().equals("")){
					while (itr.hasNext()) {
						String returnVal=itr.next().toString();
						if(newlorry.equalsIgnoreCase(returnVal)){
							updateDB=false;
							
						}

					}
					
					if(updateDB){
						
						DefaultListModel newlorryModel = (DefaultListModel) lorry_list.getModel();
						newlorryModel.addElement(newlorry);
						lorry_list.setModel(newlorryModel);
						addElements.editLorries(newlorry, "add");
						clearFields(2);
						
						//update the lorry arraylist after insertion of new element
						int sizeOfArray=newlorryModel.getSize();
						//System.out.println(newlorryModel.elementAt(0));
						lorries.clear();
						//int j=1;
						for (int i = 0; i < sizeOfArray; i++) {
							System.out.println(newlorryModel.elementAt(i));
							lorries.add(newlorryModel.elementAt(i));
						//j++;
						}
						
					}
				
					else{
					
						JOptionPane.showMessageDialog(null, "Duplicate value please Enter a different Name"); 
						ci_lorryName_textField.setText("");	
					
			
					}
				}
				else{  
					JOptionPane.showMessageDialog(null, "Please Enter a value Before Add"); 
					ci_lorryName_textField.setText("");	

				}
				
				
				
				
			}
		});
		ci_lorryAdd_btn.setBounds(91, 109, 82, 23);
		panel.add(ci_lorryAdd_btn);
		
		JLabel lblAddLorry = new JLabel("Add Lorry");
		lblAddLorry.setFont(new Font("Tahoma", Font.BOLD, 16));
		lblAddLorry.setBounds(22, 11, 95, 36);
		panel.add(lblAddLorry);
		
		listSelectionListenerlorry = new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent listSelectionEvent) {
				boolean adjust = listSelectionEvent.getValueIsAdjusting();
				// System.out.println(", Adjusting? " + adjust);
				if (!adjust) {
					JList list = (JList) listSelectionEvent.getSource();
					int selections[] = list.getSelectedIndices();
					Object selectionValues[] = list.getSelectedValues();
					for (int i = 0, n = selections.length; i < n; i++) {
						if (i == 0) {
						}
						Vallorry = (String) selectionValues[i];
						System.out.println(" Selections vallorry: "
								+ Vallorry);
					}
				}
			}
		};
		
		
		JButton ad_lorryRemoveButton = new JButton("Remove");
		ad_lorryRemoveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				// check if selection value from the list is not null
				if (Vallorry != null) {

					DefaultListModel newlorryModel = (DefaultListModel) lorry_list.getModel();
					
					//if(Common.updateTransactionsOnlorryDelete(Vallorry)){
					
					newlorryModel.removeElement(lorry_list.getSelectedValue());
					lorry_list.setModel(newlorryModel);
					addElements.editLorries(Vallorry, "remove");
					
					//update the lorry arraylist
					//set lorry arraylist with the values in the list model
					
					
					int sizeOfArray=newlorryModel.getSize();
					//System.out.println(newlorryModel.elementAt(0));
					lorries.clear();
					//int j=1;
					for (int i = 0; i < sizeOfArray; i++) {
						System.out.println(newlorryModel.elementAt(i));
						lorries.add(newlorryModel.elementAt(i));
					//j++;
					}
					//String [] newlorryArr =(String[]) newlorryModel.toArray();
					//Collections.addAll(lorry, newlorryArr); 
					}
					
					if(Vallorry==null)
						JOptionPane.showMessageDialog(null, "Select a lorry first");
					else
						JOptionPane.showMessageDialog(null, "You deleted "+ Vallorry+" lorry"); 
						//ad_region_textField.setText("");	
					
				
			}
		});
		ad_lorryRemoveButton.setBounds(384, 142, 89, 23);
		panel.add(ad_lorryRemoveButton);
		
		JPanel panel_1 = new JPanel();
		panel_1.setLayout(null);
		panel_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		panel_1.setBounds(8, 382, 483, 176);
		addElementPanel.add(panel_1);
		
		JScrollPane scrollPane_2 = new JScrollPane();
		scrollPane_2.setBounds(235, 11, 238, 127);
		panel_1.add(scrollPane_2);
		
		route_list = new JList(modelRoute);
		route_list.setFont(new Font("Arial", Font.BOLD, 11));
		route_list.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Route List", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		route_list.setBackground(Color.WHITE);
		scrollPane_2.setViewportView(route_list);
		
		JLabel label_1 = new JLabel("Name  :");
		label_1.setBounds(32, 64, 50, 14);
		panel_1.add(label_1);
		
		ci_routeName_textField = new JTextField();
		ci_routeName_textField.setColumns(10);
		ci_routeName_textField.setBounds(91, 64, 92, 14);
		panel_1.add(ci_routeName_textField);
		
		JButton ci_routeAdd_btn = new JButton("Add");
		ci_routeAdd_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
String newroute = ci_routeName_textField.getText();

				
				boolean updateDB=true;
				Iterator itr = routes.iterator();
	
				//check for the duplicate values in the list
			
				if(!newroute.trim().equals("")){
					while (itr.hasNext()) {
						String returnVal=itr.next().toString();
						if(newroute.equalsIgnoreCase(returnVal)){
							updateDB=false;
							
						}

					}
					
					if(updateDB){
						
						DefaultListModel newrouteModel = (DefaultListModel) route_list.getModel();
						newrouteModel.addElement(newroute);
						route_list.setModel(newrouteModel);
						addElements.editroutes(newroute, "add");
						clearFields(3);
						
						//update the route arraylist after insertion of new element
						int sizeOfArray=newrouteModel.getSize();
						//System.out.println(newrouteModel.elementAt(0));
						routes.clear();
						//int j=1;
						for (int i = 0; i < sizeOfArray; i++) {
							System.out.println(newrouteModel.elementAt(i));
							routes.add(newrouteModel.elementAt(i));
						//j++;
						}
						
					}
				
					else{
					
						JOptionPane.showMessageDialog(null, "Duplicate value please Enter a different Name"); 
						ci_routeName_textField.setText("");	
					
			
					}
				}
				else{  
					JOptionPane.showMessageDialog(null, "Please Enter a value Before Add"); 
					ci_routeName_textField.setText("");	

				}
				
				
			}
		});
		ci_routeAdd_btn.setBounds(91, 109, 82, 23);
		panel_1.add(ci_routeAdd_btn);
		
		JLabel lblAddRoute = new JLabel("Add Route");
		lblAddRoute.setFont(new Font("Tahoma", Font.BOLD, 16));
		lblAddRoute.setBounds(22, 11, 95, 36);
		panel_1.add(lblAddRoute);
		
		listSelectionListenerroute = new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent listSelectionEvent) {
				boolean adjust = listSelectionEvent.getValueIsAdjusting();
				// System.out.println(", Adjusting? " + adjust);
				if (!adjust) {
					JList list = (JList) listSelectionEvent.getSource();
					int selections[] = list.getSelectedIndices();
					Object selectionValues[] = list.getSelectedValues();
					for (int i = 0, n = selections.length; i < n; i++) {
						if (i == 0) {
						}
						ValRoute = (String) selectionValues[i];
						System.out.println(" Selections valroute: "
								+ ValRoute);
					}
				}
			}
		};
		
		JButton ad_routeRemoveButton = new JButton("Remove");
		ad_routeRemoveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (ValRoute != null) {

					DefaultListModel newrouteModel = (DefaultListModel) route_list.getModel();				
					newrouteModel.removeElement(route_list.getSelectedValue());
					route_list.setModel(newrouteModel);
					addElements.editroutes(ValRoute, "remove");
					int sizeOfArray=newrouteModel.getSize();					
					routes.clear();					
					for (int i = 0; i < sizeOfArray; i++) {
						System.out.println(newrouteModel.elementAt(i));
						routes.add(newrouteModel.elementAt(i));					
					}					
					}					
					if(ValRoute==null)
						JOptionPane.showMessageDialog(null, "Select a route first");
					else
						JOptionPane.showMessageDialog(null, "You deleted "+ ValRoute+" route"); 
				
			}
		});
		ad_routeRemoveButton.setBounds(384, 142, 89, 23);
		panel_1.add(ad_routeRemoveButton);
		agents_list.addListSelectionListener(listSelectionListenerAgency);
		lorry_list.addListSelectionListener(listSelectionListenerlorry);
		route_list.addListSelectionListener(listSelectionListenerroute);
		
	
	
		//////////////////////////////////////////////////////////////////////
		//Day End panel
		JPanel dayEndPanel = new JPanel();
		tabbedPane.addTab("Day End", null, dayEndPanel, null);
		dayEndPanel.setLayout(null);
		
		JLabel de_lorry_text = new JLabel("Lorry");
		de_lorry_text.setBounds(125, 44, 46, 14);
		dayEndPanel.add(de_lorry_text);
		
		final JComboBox de_lorry_comboBox = new JComboBox();
		de_lorry_comboBox.setBounds(225, 36, 129, 20);
		dayEndPanel.add(de_lorry_comboBox);
		
		JLabel de_agent_lbl = new JLabel("Sales Agent");
		de_agent_lbl.setBounds(125, 89, 90, 14);
		dayEndPanel.add(de_agent_lbl);
		
		final JComboBox de_agent_comboBox = new JComboBox();
		de_agent_comboBox.setBounds(225, 81, 129, 20);
		dayEndPanel.add(de_agent_comboBox);
		
		JLabel de_route_lbl = new JLabel("Route");
		de_route_lbl.setBounds(125, 140, 46, 14);
		dayEndPanel.add(de_route_lbl);
		
		final JComboBox de_route_comboBox = new JComboBox();
		de_route_comboBox.setBounds(225, 132, 129, 20);
		dayEndPanel.add(de_route_comboBox);
		
		JButton de_save_btn = new JButton("Save");
		de_save_btn.setBounds(126, 427, 89, 23);
		dayEndPanel.add(de_save_btn);
		
		JButton de_clear_btn = new JButton("Clear");
		de_clear_btn.setBounds(225, 427, 89, 23);
		dayEndPanel.add(de_clear_btn);
		
		JLabel de_date_lbl = new JLabel("Date");
		de_date_lbl.setBounds(125, 184, 46, 14);
		dayEndPanel.add(de_date_lbl);
		
		de_date_text = new JTextField();
		de_date_text.setBounds(225, 176, 129, 20);
		dayEndPanel.add(de_date_text);
		de_date_text.setColumns(10);
		
		
		JButton de_datePick_btn = new JButton("");
		de_datePick_btn.setIcon(new ImageIcon(AddToLorry.class.getResource("/com/midi/wholesale/resources/date.gif")));
		de_datePick_btn.setBounds(364, 175, 21, 23);
		dayEndPanel.add(de_datePick_btn);
		
		JButton de_view_btn = new JButton("View");
		de_view_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
			}
		});
		de_view_btn.setBounds(172, 207, 89, 23);
		dayEndPanel.add(de_view_btn);
		
		de_datePick_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				de_date_text.setText(new DatePicker(home).setPickedDate());
			}
		});
		
		
	
		//////////////////////////////////////////////////////////////////////
		//Stock Details panel
		JPanel stockDetailPanel = new JPanel();
		tabbedPane.addTab("Stock Detail", null, stockDetailPanel, null);
		stockDetailPanel.setLayout(null);
		
		JLabel sd_itemName_lbl = new JLabel("Item Name");
		sd_itemName_lbl.setBounds(130, 49, 73, 14);
		stockDetailPanel.add(sd_itemName_lbl);
		
		final JComboBox sd_itemName_comboBox = new JComboBox();
		sd_itemName_comboBox.setBounds(253, 46, 133, 20);
		stockDetailPanel.add(sd_itemName_comboBox);
		
		JLabel sd_amount_lbl = new JLabel("Amount");
		sd_amount_lbl.setBounds(130, 93, 61, 14);
		stockDetailPanel.add(sd_amount_lbl);
		
		sd_amount_text = new JTextField();
		sd_amount_text.setBounds(253, 90, 133, 20);
		stockDetailPanel.add(sd_amount_text);
		sd_amount_text.setColumns(10);
		
		JButton sd_save_btn = new JButton("Save");
		sd_save_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Object selected_item = sd_itemName_comboBox.getSelectedItem();
				String amount=sd_amount_text.getText();
				if(selected_item.equals("Choose Item")||selected_item==null||amount==null||amount.equals(""))
					{
						JOptionPane.showMessageDialog(null,"Please enter all fields...");
						
					}
				else
					{
					try {						
						
						Item new_item=(Item) selected_item;	
						int new_amount = Integer.parseInt(sd_amount_text.getText());
						int itemId=new_item.getId();
						boolean IsRecorded=new StockDetail().submitData(new_item.getId(),new_amount);
											
						/*
						
						if(IsRecorded){
							JOptionPane.showMessageDialog(null, "Bill Entry Added Successfully.");
							be_billNo.setText("");
							be_amnt_textField.setText("");
							be_des_textArea.setText("");
							be_agency_comboBox.setSelectedIndex(0);
							be_region_comboBox.setSelectedIndex(0);
							be_shop_comboBox.setSelectedIndex(0);*/
						//}
						
						
					} catch (NumberFormatException nfe) {
						JOptionPane.showMessageDialog(null, "Invalid Format...");
					}
						
					}		

		
			}
		});
		sd_save_btn.setBounds(156, 147, 89, 23);
		stockDetailPanel.add(sd_save_btn);
		
		JButton sd_clear_btn = new JButton("Clear");
		sd_clear_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				sd_itemName_comboBox.setSelectedIndex(0);
				sd_amount_text.setText("");
			}
		});
		sd_clear_btn.setBounds(258, 147, 89, 23);
		stockDetailPanel.add(sd_clear_btn);
		
		JPanel panel_2 = new JPanel();
		panel_2.setLayout(null);
		panel_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		panel_2.setBounds(10, 242, 483, 176);
		stockDetailPanel.add(panel_2);
		
		JScrollPane scrollPane_3 = new JScrollPane();
		scrollPane_3.setBounds(235, 11, 238, 127);
		panel_2.add(scrollPane_3);
		
		item_list = new JList(modelItem);
		item_list.setFont(new Font("Iskoola Pota", Font.BOLD, 11));
		item_list.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Item List", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		item_list.setBackground(Color.WHITE);
		scrollPane_3.setViewportView(item_list);
		
		JLabel label_2 = new JLabel("Name  :");
		label_2.setBounds(32, 64, 50, 14);
		panel_2.add(label_2);
		
		ci_itemName_textField = new JTextField();
		ci_itemName_textField.setFont(new Font("Iskoola Pota", Font.PLAIN, 11));
		ci_itemName_textField.setColumns(10);
		ci_itemName_textField.setBounds(91, 64, 92, 14);
		panel_2.add(ci_itemName_textField);
		
		JButton ci_itemAdd_btn = new JButton("Add");
		ci_itemAdd_btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
String newitem = ci_itemName_textField.getText();

				
				boolean updateDB=true;
				Iterator itr = items.iterator();
	
				//check for the duplicate values in the list
			
				if(!newitem.trim().equals("")){
					while (itr.hasNext()) {
						String returnVal=itr.next().toString();
						if(newitem.equalsIgnoreCase(returnVal)){
							updateDB=false;
							
						}

					}
					
					if(updateDB){
						
						DefaultListModel newitemModel = (DefaultListModel) item_list.getModel();
						newitemModel.addElement(newitem);
						item_list.setModel(newitemModel);
						addElements.edititems(newitem, "add");
						clearFields(4);
						
						sd_itemName_comboBox.removeAllItems();
						sd_itemName_comboBox.insertItemAt("Choose Item",0);
						sd_itemName_comboBox.setSelectedIndex(0);
						
						
						//update the item arraylist after insertion of new element
						int sizeOfArray=newitemModel.getSize();
						//System.out.println(newitemModel.elementAt(0));
						items.clear();
						//int j=1;
						for (int i = 0; i < sizeOfArray; i++) {
							System.out.println(newitemModel.elementAt(i));
							items.add(newitemModel.elementAt(i));
							sd_itemName_comboBox.addItem(newitemModel.elementAt(i));
						//j++;
						}
						
					}
				
					else{
					
						JOptionPane.showMessageDialog(null, "Duplicate value please Enter a different Name"); 
						ci_itemName_textField.setText("");	
					
			
					}
				}
				else{  
					JOptionPane.showMessageDialog(null, "Please Enter a value Before Add"); 
					ci_itemName_textField.setText("");	

				}
				
				
			}
		});
		ci_itemAdd_btn.setBounds(91, 109, 82, 23);
		panel_2.add(ci_itemAdd_btn);
		
		JLabel lblAddItem_1 = new JLabel("Add Item Category");
		lblAddItem_1.setFont(new Font("Tahoma", Font.BOLD, 16));
		lblAddItem_1.setBounds(22, 11, 177, 36);
		panel_2.add(lblAddItem_1);
		
		listSelectionListeneritem = new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent listSelectionEvent) {
				boolean adjust = listSelectionEvent.getValueIsAdjusting();
				// System.out.println(", Adjusting? " + adjust);
				if (!adjust) {
					JList list = (JList) listSelectionEvent.getSource();
					int selections[] = list.getSelectedIndices();
					Object selectionValues[] = list.getSelectedValues();
					for (int i = 0, n = selections.length; i < n; i++) {
						if (i == 0) {
						}
						ValItem = (String) selectionValues[i];
						System.out.println(" Selections valitem: "
								+ ValItem);
					}
				}
			}
		};
		
		JButton ad_itemRemoveButton = new JButton("Remove");
		ad_itemRemoveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (ValItem != null) {
					
					sd_itemName_comboBox.removeAllItems();
					sd_itemName_comboBox.insertItemAt("Choose Item",0);
					sd_itemName_comboBox.setSelectedIndex(0);
					
					DefaultListModel newitemModel = (DefaultListModel) item_list.getModel();				
					newitemModel.removeElement(item_list.getSelectedValue());
					item_list.setModel(newitemModel);
					addElements.edititems(ValItem, "remove");
					int sizeOfArray=newitemModel.getSize();					
					items.clear();					
					for (int i = 0; i < sizeOfArray; i++) {
						System.out.println(newitemModel.elementAt(i));
						items.add(newitemModel.elementAt(i));	
						sd_itemName_comboBox.addItem(newitemModel.elementAt(i));
					}					
					}					
					if(ValItem==null)
						JOptionPane.showMessageDialog(null, "Select a item first");
					else
						JOptionPane.showMessageDialog(null, "You deleted "+ ValItem+" item"); 
						
				
			}
		});
		ad_itemRemoveButton.setBounds(384, 142, 89, 23);
		panel_2.add(ad_itemRemoveButton);
		item_list.addListSelectionListener(listSelectionListeneritem);
		
		//////////////////////////////////////////////////////////////////////
		//reports panel
		JPanel reportPanel = new JPanel();
		tabbedPane.addTab("Reports", null, reportPanel, null);
		reportPanel.setLayout(null);
		
		JLabel selectDatelbl = new JLabel("Select Dates");
		selectDatelbl.setFont(new Font("Tahoma", Font.BOLD, 16));
		selectDatelbl.setBounds(21, 11, 126, 30);
		reportPanel.add(selectDatelbl);
		
		JLabel fromDateLbl = new JLabel("From");
		fromDateLbl.setBounds(80, 65, 46, 14);
		reportPanel.add(fromDateLbl);
		
		textFromDate = new JTextField();
		textFromDate.setBounds(165, 62, 168, 20);
		reportPanel.add(textFromDate);
		textFromDate.setColumns(10);
		
		JButton buttonFromCalendar = new JButton("");
		buttonFromCalendar.setIcon(new ImageIcon(AddToLorry.class.getResource("/com/midi/wholesale/resources/date.gif")));
		buttonFromCalendar.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
		textFromDate.setText(new DatePicker(home).setPickedDate());
		}
		});
		buttonFromCalendar.setBounds(343, 59, 21, 23);
		reportPanel.add(buttonFromCalendar);
		
		JLabel toDateLbl = new JLabel("To");
		toDateLbl.setBounds(80, 95, 46, 14);
		reportPanel.add(toDateLbl);
		
		textToDate = new JTextField();
		textToDate.setBounds(165, 92, 168, 20);
		reportPanel.add(textToDate);
		textToDate.setColumns(10);
		
		JButton buttonToCalendar = new JButton("");
		buttonToCalendar.setIcon(new ImageIcon(AddToLorry.class.getResource("/com/midi/wholesale/resources/date.gif")));
		buttonToCalendar.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent arg0) {
		textToDate.setText(new DatePicker(home).setPickedDate());
		}
		});
		buttonToCalendar.setBounds(343, 89, 21, 23);
		reportPanel.add(buttonToCalendar);
		
		JButton viewSumaryBtn = new JButton("View Summary");
		viewSumaryBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String date = textFromDate.getText();
				HashMap<String,Object> params = new HashMap<String,Object>();
				params.put("date", date);
				if(date.equals("")){
					JOptionPane.showMessageDialog(null, "Please enter the Date..!");
				}else{
					new ViewGenerator(params,ViewGenerator.REPORT_TYPE_CREDIT_OVERDUE).setVisible(true);
				}
				
			}
		});
		viewSumaryBtn.setBounds(152, 141, 152, 23);
		reportPanel.add(viewSumaryBtn);
				

		/*Check which tab is selected */
		tabbedPane.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				int tabId = tabbedPane.getSelectedIndex();
				System.out.println(tabId);

				switch (tabId) {

				case 0:	
					//Lorry details tab
					ld_lorry_combo.removeAllItems();
					ld_lorry_combo.insertItemAt("Choose Lorry", 0);
					ld_lorry_combo.setSelectedIndex(0);
					
					ld_agent_combo.removeAllItems();
					ld_agent_combo.insertItemAt("Choose Agent",0);
					ld_agent_combo.setSelectedIndex(0);					
				
					ld_route_combo.removeAllItems();
					ld_route_combo.insertItemAt("Choose Route",0);
					ld_route_combo.setSelectedIndex(0);
					
					
					ArrayList<Lorry> lorryList = Common.loadlorries();
					for (Lorry lorry : lorryList) {
						ld_lorry_combo.addItem(lorry);
					}
					
					ArrayList<Agent> agentList = Common.loadagents();
					for (Agent agent : agentList) {
						ld_agent_combo.addItem(agent);
					}
					
					ArrayList<Route> routeList = Common.loadroutes();
					for (Route route : routeList) {
						ld_route_combo.addItem(route);
					}
					break;

				case 1:
				//Add Element tab
					int id=1;
					boolean check=PasswordChecker.checkResult(id);
				   // Uses boolean to determine if password is valid
				   if(check==true)
				   {
					   System.out.println("Correct password");
					   
					   if (addElementTabClickCount == 0) {
						   
						   Object[] listObject = addElements
									.loadDataAddElementsFrame();

							 agents = (ArrayList) listObject[0];
							 lorries = (ArrayList) listObject[1];
							 routes = (ArrayList) listObject[2];
						   
							 System.out.println(", agency? " +agents.size());
							 
							Iterator itr = agents.iterator();
								int count = 0;
								while (itr.hasNext()) {

									modelAgency.add(count, itr.next());
									count++;

							}  
								
								itr = lorries.iterator();
								count = 0;
								while (itr.hasNext()) {

									modelLorry.add(count, itr.next());
									count++;

							}	
								
								itr = routes.iterator();
								count = 0;
								while (itr.hasNext()) {

									modelRoute.add(count, itr.next());
									count++;

							}
							   
					   }
					   
					   
				   }
				   else
			       {
			       JOptionPane.showMessageDialog(null, "Enter Correct Password");
			       tabbedPane.setSelectedIndex(0);
			       }
					
					
					
					break;
				case 2:
					//Day End tab
					de_lorry_comboBox.removeAllItems();
					de_lorry_comboBox.insertItemAt("Choose lorry",0);
					de_lorry_comboBox.setSelectedIndex(0);
					
					de_agent_comboBox.removeAllItems();
					de_agent_comboBox.insertItemAt("Choose Agent",0);
					de_agent_comboBox.setSelectedIndex(0);					
				
					de_route_comboBox.removeAllItems();
					de_route_comboBox.insertItemAt("Choose Route",0);
					de_route_comboBox.setSelectedIndex(0);
					
					ArrayList<Lorry> de_lorryList = Common.loadlorries();
					for (Lorry lorry : de_lorryList) {
						de_lorry_comboBox.addItem(lorry);
					}
					
					ArrayList<Agent> de_agentList = Common.loadagents();
					for (Agent agent : de_agentList) {
						de_agent_comboBox.addItem(agent);
					}
					
					ArrayList<Route> de_routeList = Common.loadroutes();
					for (Route route : de_routeList) {
						de_route_comboBox.addItem(route);
					}
					
					break;
				case 3:
					//Stock Detail tab
					sd_itemName_comboBox.removeAllItems();
					sd_itemName_comboBox.insertItemAt("Choose Item",0);
					sd_itemName_comboBox.setSelectedIndex(0);
					
					ArrayList<Item> sd_itemList = Common.loadItems();
					for (Item item : sd_itemList) {
						items.add(item.toString());
						sd_itemName_comboBox.addItem(item);
						//System.out.println(item.toString());
						
						
					}
					
					Iterator itr = items.iterator();
					int count = 0;
					while (itr.hasNext()) {

						modelItem.add(count, itr.next());
						count++;

				}
					
					break;					
					
				}
			}
		
		});
	
				
	}
	
	
	private void clearFields(int x) {
      
	if(x==1)
		ci_agentName_textField.setText("");
	if(x==2)
		ci_lorryName_textField.setText("");
	if(x==3)
		ci_routeName_textField.setText("");	
	if(x==4)
		ci_itemName_textField.setText("");

	}
}
